<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 09/10/2017
 * Time: 12:41
 */
namespace backend\controllers;

use common\models\ar\MoneyChangeDirection;
use common\models\ar\MoneyWithdraw;
use common\models\ar\User;
use common\models\ar\UserBrokers;
use common\models\ar\UserInfoDetail;
use common\models\ar\UserMoney;
use common\models\ar\UserMoneyChangerecord;
use common\models\Common;
use common\models\MoneyDao;
use common\models\Pay;
use common\models\WithdrawDao;
use common\models\ar\UserBrokerCommissionGrantRecord;
class WithdrawController extends BackendController
{
    public function actionLists()
    {
        $dl="";
        $req = \Yii::$app->request;
        $isRender = $req->get('isRender', 1);//1为搜索页面，2为异步获取代理记录
        $userModel = UserBrokers::findOne(\Yii::$app->user->identity->id);
        $levelInfo = Common::getLevelsInfo($userModel->level);
        $status = (int)$req->get('status', -1);
        $pClientSN = trim($req->get('clientSN', ''));
        $pageNo = (int)$req->get('pageNo', 1);
        $pageSize = \Yii::$app->params['pageSize'];

        //日期
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;

        $uid = -1;

        if ($pClientSN != '') {
            if (is_numeric($pClientSN)) {

                //数字类型，以客户编号搜索
                if (UserBrokers::findOne(['loginName'=>$pClientSN])){
                    $tmp=UserBrokers::findOne(['loginName'=>$pClientSN]);
                    $uid=$tmp->id;
                    $dl=1;
                }else if(User::findOne(['loginName'=>$pClientSN])){
                    $tmp=User::findOne(['loginName'=>$pClientSN]);
                    $uid=$tmp->userID;
                    $dl=2;
                }else{
                    $uid=0;
                }
            }else {
                //非数字类型，以姓名搜索
                $uid=0;
            }
        }
        //直接返回
        if ($uid == 0) {
            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => 0,
                'sumMoney' => 0,
                'lists' => [],
            ];
        } else {
            $res = WithdrawDao::history(
                $status,
                $uid,
                $from,
                $to,
                $pageNo,
                $pageSize,
                $dl
            );
            $return = [
                'pageNo' => $pageNo,
                'pageTotal' => ceil($res['total'] / $pageSize),
                'sumMoney' => $res['sumMoney'],
                'lists' => $res['lists'],
                'is_first' => $levelInfo['is_first'],
            ];
        }
        if ($isRender == 1) {
            $return['from'] = $from;
            $return['to'] = $to - 1;

            return $this->renderPartial('lists', $return);
        } else {
            exit(json_encode($return));
        }
    }

    /**
     * 确定出金的操作方向
     */
    public function actionConfirmForm()
    {
        $id = (int)\Yii::$app->request->get('id', 0);
        $withdrawObj = MoneyWithdraw::findOne($id);
        if (!$withdrawObj) {
            exit('记录不存在');
        }

        if ($withdrawObj->status != 0) {
            exit('记录状态已变化');
        }
        $userObj = User::findOne($withdrawObj->userID);
        $withdrawUID = $withdrawObj->userID;
        $withdrawUserObj = User::findOne($withdrawUID);
        if ($userObj){
            $realNameInfo = UserInfoDetail::find()
                ->select("user_info_field.key,user_info_detail.field_value")
                ->leftJoin('user_info_field', 'user_info_detail.field_id = user_info_field.id')
                ->where(['user_info_detail.userID' => $withdrawUserObj->userID])
                ->andWhere(['user_info_field.menu_id' => 6])
                ->andWhere("user_info_field.id IN (71,78,81,82,85)")
                ->orderBy(['user_info_field.sort' => SORT_ASC])
                ->asArray()
                ->all();
        }else{
            $userObj = UserBrokers::findOne($withdrawObj->userID);
            $realNameInfo="1";
        }
        return $this->renderPartial('confirm-form', [
            'withdrawObj' => $withdrawObj,
            'direction' => MoneyChangeDirection::findOne($withdrawObj->direction)->name,
            'userObj' => $userObj,
            'realNameInfo' => $realNameInfo
        ]);
    }

    /**
     * 确定出金
     */
    public function actionConfirm()
    {
        date_default_timezone_set("Asia/Shanghai");
        $date = date('Y-m-d H:i:s', time());
        $uid = \Yii::$app->user->identity->id;
        $id = (int)\Yii::$app->request->post('id', 0);
        $obj = MoneyWithdraw::findOne($id);
        $time=time();
        if (!$obj) {
            $code = 1002;
            $msg = "记录不存在";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->status != 0) {
            $code = 1003;
            $msg = "记录状态已变化";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $type = (int)\Yii::$app->request->post('type', 0);
        if (!in_array($type, [1, 2])) {
            $code = 1004;
            $msg = "操作类别不符";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        if (UserBrokers::findOne(['id'=>$obj['userID']])){
         $transaction=\Yii::$app->db->beginTransaction();
         try{
             date_default_timezone_set("Asia/Shanghai");
             $date = date('Y-m-d H:i:s', $time);
             $db = \Yii::$app->db;
             $UserBroker_Record = new UserBrokerCommissionGrantRecord();
             $UserBroker_Record->brokerId=$obj['userID'];
             $UserBroker_Record->grantMoney=$obj['money'];
             $UserBroker_Record->time=$date;
             $UserBroker_Record->grantdesc="在线提现";
             $UserBroker_Record->tradeId=0;
             $UserBroker_Record->save(false);
             $sql="SELECT id FROM `user_broker_commission_grant_record` WHERE 
                  time=(SELECT MAX(time) FROM `user_broker_commission_grant_record` WHERE brokerId=:userID)";
             $extra_id=$db->createCommand($sql, [
                 ":userID" => $obj['userID']
             ])->queryAll();
             $sql = "INSERT INTO `change_cache` (`userid`,`change_type`,`extra_id`) values (:userID,:type,:extra_id)";
             $db->createCommand($sql, [":userID" => $obj['userID'],":type"=>4,':extra_id'=>$extra_id[0]['id']])->execute();
             $transaction->commit();
         }catch (Exception $e){
//             $error = $e->getMessage();  //获取抛出的错误
             $transaction->rollBack();
         }
        }
        //管理员备注
        $remark = strip_tags(\Yii::$app->request->post('remark', ''));
        $transaction=\Yii::$app->db->beginTransaction();
        try{
            $users=UserMoneyChangerecord::findOne(['id'=>$obj->user_money_change_id]);
            if ($users){
                $users->changeDesc="提现申请:申请成功".$users->changeTime;
                $users->changeTime=$date;
                $users->save();
            }
            $obj->admin_remark = $remark;
            $obj->status = 6;
            $obj->resp_code = '000000';
            $obj->uid_admin = $uid;
            $obj->withdraw_end_time = time();
            $obj->save(false);
            $transaction->commit();
        }catch (Exception $e){
            $transaction->rollBack();
            throw $e;
        }
        $users=UserMoneyChangerecord::findOne(['id'=>$obj->user_money_change_id]);
        if ($users) {
            $users->changeDesc="提现申请:申请成功".$users->changeTime;
            $users->changeTime=$date;
            $users->save();
        }
        $obj->admin_remark = $remark;
        $obj->status = 6;
        $obj->resp_code = '000000';
        $obj->uid_admin = $uid;
        $obj->withdraw_end_time = time();
        $obj->save(false);
        $code = 1;
        $msg = '操作成功';
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    public function actionCancel()
    {
        $uid = \Yii::$app->user->identity->id;
        $id = \Yii::$app->request->get('id', 0);
        $obj = MoneyWithdraw::findOne($id);
//        var_dump($obj['userID']);
//        exit();
        if (!$obj) {
            $code = 1002;
            $msg = "记录不存在";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        if ($obj->status != 0) {
            $code = 1003;
            $msg = "记录状态已变化";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $obj->uid_admin = $uid;
        $obj->save();
        //反方向入金
        switch ($obj->direction) {
            case 2:
                $direction = 1;
                break;
            case 8:
                $direction = 9;
                break;
            case 18:
                $direction = 17;
                break;
            default:
                $code = 1003;
                $msg = '类型错误';
                exit(json_encode(['code' => $code, 'msg' => $msg]));
                break;
        }
        $time = time();
        $ip = \Yii::$app->request->getUserIP();
        $ua = \Yii::$app->request->getUserAgent();
        if (UserBrokers::findOne(['id'=>$obj['userID']])){
            $bool = MoneyDao::inOut(0, $obj->userID, $direction, $obj->money, $time, 1, $ip, $ua, '平台取消',1);
        }else{
            $bool = MoneyDao::inOut(0, $obj->userID, $direction, $obj->money, $time, 1, $ip, $ua, '平台取消');
        }

        if (!$bool) {
            $code = 0;
            $msg = "操作失败";
        } else {
           $obj->status = 4;
           $obj->withdraw_start_time = $time;
           $obj->withdraw_end_time = $time;
           $obj->data_response = json_encode(['msg' => '平台取消']);
           $obj->uid_admin = $uid;
           $obj->save(false);

            $code = 1;
            $msg = "操作成功";
        }

        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }
}
